﻿using System;

namespace TestApplication.Domain.Models
{
    public class UnitOfWork : IDisposable
    {
        private readonly DbContext _dbContext;

        private ProductRepository _productRepository;

        private StoreRepository _storeRepository;

        public UnitOfWork()
        {
            _dbContext = new DbContext();
        }

        public UnitOfWork(DbContext context)
        {
            _dbContext = context;
        }

        public DbContext Context
        {
            get { return _dbContext; }
        }

        public ProductRepository ProductRepository
        {
            get { return _productRepository ?? (_productRepository = new ProductRepository(_dbContext)); }
        }

        public StoreRepository StoreRepository
        {
            get { return _storeRepository ?? (_storeRepository = new StoreRepository(_dbContext)); }
        }

        public void SaveChanges()
        {
            _dbContext.SaveChanges();
        }

        #region Dispose

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _dbContext.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}